package sensor;

import grammer.components.ObjectEnum;
import houseHold.HouseHoldObject;
import houseHold.Room;

import java.util.Vector;

import timer.Time;
import weather.CurrentWeather;
import constants.Constants;

public class LumenCalculator {
	private static Vector<Integer> list = new Vector<Integer>();
	private static Vector<Integer> values = new Vector<Integer>();
	private static boolean init = initList();

	public static double compute(Room r, int time) {
		double candela = 0;
		double tval = 0;
		if (time < Time.dawnTime || time > Time.duskTime)
			tval = 0;
		else {
			if (time < Time.getMidDay())
				tval = time - Time.dawnTime;
			else {
				tval = Time.duskTime - time;
			}
			tval = tval / Time.getMidDay();
		}
		candela = 10000 * tval * CurrentWeather.getInstance().getWeatherCoef()
				+ getLightLum(r) * Math.min(4, 1 / (tval));
		double surface = ((double) (r.getWidth() + r.getLength())) / 100;
		if (surface == 0)
			surface = 1;
		return candela / surface;
	}

	public static int getAverage(int con) {
		if (con == 0)
			return 0;
		int avg = 0;
		for (int i = 0; i < list.size(); i++) {
			if (con > list.get(i)) {
				if (i > 1) {
					avg = (values.get(i - 1) + values.get(i)) / 2;
					break;
				} else {
					avg = values.get(i);
					break;
				}
			}
			if (con == list.get(i)) {
				avg = values.get(i);
				break;
			}
		}

		return avg;
	}

	private static int getLightLum(Room r) {
		HouseHoldObject light = r.getItemByType(ObjectEnum.LIGHT);
		int lc = 0;
		HouseHoldObject tv = r.getItemByType(ObjectEnum.TELEVISION);
		int tvc = 0;
		HouseHoldObject cpu = r.getItemByType(ObjectEnum.COMPUTER);
		int cpuc = 0;
		if (light != null)
			if (light.isActive())
				lc = light.getConsumption();
		if (tv != null)
			if (tv.isActive())
				tvc = tv.getConsumption();
		if (cpu != null)
			if (cpu.isActive())
				cpuc = cpu.getConsumption();
		int res = cpuc / 2 + tvc / 2 + getAverage(lc);
		int variable = 0;
		if (res >= 1) {
			variable = res / 25;
		} else
			variable = 1;
		int avg = Constants.rd.nextInt(variable);
		boolean sw = Constants.rd.nextBoolean();
		if (sw)
			avg = avg * (-1);
		return res + avg;
	}

	private static boolean initList() {
		list.add(5);
		values.add(25);
		list.add(15);
		values.add(110);
		list.add(25);
		values.add(200);
		list.add(35);
		values.add(350);
		list.add(40);
		values.add(500);
		list.add(50);
		values.add(700);
		list.add(55);
		values.add(800);
		list.add(60);
		values.add(850);
		list.add(65);
		values.add(1000);
		list.add(70);
		values.add(1100);
		list.add(75);
		values.add(1200);
		list.add(90);
		values.add(1450);
		list.add(95);
		values.add(1600);
		list.add(100);
		values.add(1700);
		list.add(135);
		values.add(2350);
		list.add(150);
		values.add(2850);
		list.add(200);
		values.add(3900);
		list.add(300);
		values.add(6200);
		return true;
	}
}
